//
//  GPSExerciseInfoTableViewCell.swift
//  DaFit
//
//  Created by Paul on 2022/10/27.
//  Copyright © 2022 sylar. All rights reserved.
//

import UIKit
import MYModule
import CRPSmartRing

open class GPSTrainingInfoTableViewCell: UITableViewCell {
    
    private var line1StackView = UIStackView()
    private var line2StackView = UIStackView()
    
    public let goalLabel: UILabel = {
        let lab = UILabel()
        lab.textColor = .black
        lab.font = .systemFont(ofSize: 40, weight: .heavy)
        lab.text = "0.00"
        return lab
    }()
    
    public let goalSubLabel: UILabel = {
        let lab = UILabel()
        lab.textColor = .black
        lab.font = .systemFont(ofSize: 20)
        lab.text = Unit.sharedInstance.myType.baseDistance.name
        return lab
    }()
    
    public let goalStackView: UIStackView = {
        let stackView = UIStackView()
        stackView.distribution = .fillProportionally
        stackView.axis = .horizontal
        stackView.alignment = .lastBaseline
        return stackView
    }()
    
    public let distanceStackView:InfoStackView = {
        let infoView = InfoStackView(frame: CGRect(x: 0, y: 0, width: kScreenWidth/2, height: 30))
        infoView.setTitle(title: "--")
        infoView.setSubTitle(subTitle: "gps_training_goal_setting_distance_title".language)
        return infoView
    }()
    
    public let timeStackView:InfoStackView = {
        let infoView = InfoStackView(frame: CGRect(x: 0, y: 0, width: kScreenWidth/2, height: 30))
        infoView.setTitle(title: "--:--:--")
        infoView.setSubTitle(subTitle: "gps_training_time".language)
        return infoView
    }()
    public let paceLabelStackView:InfoStackView = {
        let infoView = InfoStackView(frame: CGRect(x: 0, y: 0, width: kScreenWidth/2, height: 30))
        infoView.setTitle(title: "--'--''")
        infoView.setSubTitle(subTitle: "gps_training_pace".language)
        return infoView
    }()
    public let kcalLabelStackView:InfoStackView = {
        let infoView = InfoStackView(frame: CGRect(x: 0, y: 0, width: kScreenWidth/2, height: 30))
        infoView.setTitle(title: "--")
        infoView.setSubTitle(subTitle: "gps_training_kcal".language)
        return infoView
    }()
    public let rateLabelStackView:InfoStackView = {
        let infoView = InfoStackView(frame: CGRect(x: 0, y: 0, width: kScreenWidth/2, height: 30))
        infoView.setTitle(title: "--")
        infoView.setSubTitle(subTitle: "gps_training_finish_rate".language)
        return infoView
    }()
    public let stepLabelStackView:InfoStackView = {
        let infoView = InfoStackView(frame: CGRect(x: 0, y: 0, width: kScreenWidth/2, height: 30))
        infoView.setTitle(title: "--")
        infoView.setSubTitle(subTitle: "gps_training_finish_total_steps".language)
        return infoView
    }()
    public let elevationLabelStackView:InfoStackView = {
        let infoView = InfoStackView(frame: CGRect(x: 0, y: 0, width: kScreenWidth/2, height: 30))
        infoView.setTitle(title: "--")
        infoView.setSubTitle(subTitle: "gps_training_finish_elevation".language)
        return infoView
    }()
    public let minHrLabelStackView:InfoStackView = {
        let infoView = InfoStackView.init(true)
        infoView.setTitle(title: "--")
        infoView.setSubTitle(subTitle: "home_dyheart_low".language)
        return infoView
    }()
    public let avgHrLabelStackView:InfoStackView = {
        let infoView = InfoStackView.init(true)
        infoView.setTitle(title: "--")
        infoView.setSubTitle(subTitle: "home_dyheart_avg_heart".language)
        return infoView
    }()
    public let MaxHrLabelStackView:InfoStackView = {
        let infoView = InfoStackView.init(true)
        infoView.setTitle(title: "--")
        infoView.setSubTitle(subTitle: "home_dyheart_high".language)
        return infoView
    }()
    
    public var minHrStr: String = "" {
        didSet{
            if minHrStr != oldValue{
                minHrLabelStackView.setTitle(title: minHrStr)
            }
        }
    }
    public var avgHrStr: String = "" {
        didSet{
            if avgHrStr != oldValue{
                avgHrLabelStackView.setTitle(title: avgHrStr)
            }
        }
    }
    public var maxHrStr: String = "" {
        didSet{
            if maxHrStr != oldValue{
                MaxHrLabelStackView.setTitle(title: maxHrStr)
            }
        }
    }
    
    //MARK: - 初始化
    public override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.selectionStyle = .none
        makeUI()
    }
    
    public required init?(coder: NSCoder) {
        super.init(coder: coder)
        
        makeUI()
    }
    
    open func makeUI() {
        
        self.backgroundColor = UIColor.darkBackground
        
        let boxView = UIView()
        boxView.backgroundColor = .white
        boxView.layer.cornerRadius = 18.0
        
        contentView.addSubview(boxView)
        boxView.snp.makeConstraints { make in
            make.top.centerX.width.equalToSuperview()
            make.bottom.equalToSuperview().offset(-20)
        }
        
        let topBgView = UIView()
        boxView.addSubview(topBgView)
        topBgView.backgroundColor = boxView.backgroundColor
        topBgView.snp.makeConstraints { make in
            make.top.leading.trailing.equalToSuperview()
            make.height.equalTo(30)
        }
        
        goalStackView.addArrangedSubview(goalLabel)
        goalStackView.addArrangedSubview(goalSubLabel)
        boxView.addSubview(goalStackView)
        
        goalStackView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(25)
            make.height.equalTo(48)
        }
        
        let lineView = UIView()
        boxView.addSubview(lineView)
        lineView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(goalStackView.snp.bottom).offset(25)
            make.width.equalToSuperview().offset(-40)
            make.height.equalTo(4)
        }
        lineView.layer.cornerRadius = 2
        lineView.layer.masksToBounds = true
        setGradientbar(barView: lineView)
        
        let slowLab = UILabel()
        slowLab.textColor = UIColor.GPSTraining.slow
        slowLab.font = .systemFont(ofSize: 10)
        slowLab.text = "gps_training_finish_route_slow".language
        slowLab.textAlignment = .left
        
        let fastLab = UILabel()
        fastLab.textColor = UIColor.GPSTraining.fast
        fastLab.font = .systemFont(ofSize: 10)
        fastLab.text = "gps_training_finish_route_fast".language
        fastLab.textAlignment = .right
        
        let lineTitleStackView = UIStackView(arrangedSubviews: [slowLab, fastLab])
        lineTitleStackView.distribution = .fillEqually
        lineTitleStackView.axis = .horizontal
        lineTitleStackView.alignment = .fill
        
        boxView.addSubview(lineTitleStackView)
        lineTitleStackView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.width.equalTo(lineView)
            make.bottom.equalTo(lineView.snp.top).offset(-3)
        }
        
        line1StackView = UIStackView(arrangedSubviews: [timeStackView,paceLabelStackView,kcalLabelStackView])
        line1StackView.distribution = .fillEqually
        line1StackView.axis = .horizontal
        line1StackView.alignment = .fill
        line1StackView.spacing = 5
        
        line2StackView = UIStackView(arrangedSubviews: [rateLabelStackView,stepLabelStackView,elevationLabelStackView])
        line2StackView.distribution = .fillEqually
        line2StackView.axis = .horizontal
        line2StackView.alignment = .fill
        line2StackView.spacing = 5
        
        let line3StackView = UIStackView(arrangedSubviews: [minHrLabelStackView,avgHrLabelStackView,MaxHrLabelStackView])
        line3StackView.distribution = .fillEqually
        line3StackView.axis = .horizontal
        line3StackView.alignment = .fill
        line3StackView.spacing = 5
        
        let allStackView = UIStackView(arrangedSubviews:
                                        [line1StackView,
                                         line2StackView,
//                                         line3StackView
                                        ])
        allStackView.distribution = .fillEqually
        allStackView.axis = .vertical
        allStackView.alignment = .fill
        allStackView.spacing = 15
        
        boxView.addSubview(allStackView)
        allStackView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.width.equalToSuperview().offset(-40)
            make.top.equalTo(lineView.snp.bottom).offset(25)
            make.bottom.equalToSuperview().offset(-20)
        }
    }
    
    public func bindModel(_ model: GPSTrainingModel?) {
        
        guard let model = model else {
            return
        }
        
        let paceString = self.returnPaceString(pace: self.calculationPace(distance: Double(model.distance), duration: Double(model.vaildTime)))
        self.paceLabelStackView.setTitle(title: paceString)
        
        let distanceString = self.returnDistanceString(distance: Double(model.distance))
        self.distanceStackView.setTitle(title: distanceString)
        
        let durationString = self.returnDurationString(duration: model.vaildTime)
        self.timeStackView.setTitle(title: durationString)
        
        let kcalString = model.kcal.normalTitle
        self.kcalLabelStackView.setTitle(title: kcalString)
        
        let rateString = self.returnRateString(step: Double(model.step), duration: Double(model.vaildTime))
        self.rateLabelStackView.setTitle(title: rateString)
        
        let stepString = model.step.normalTitle
        self.stepLabelStackView.setTitle(title: stepString)
        
        let elevationString = model.getElevation()
        self.elevationLabelStackView.setTitle(title: elevationString)
                
        switch CRPSmartRing.CRPTrainingGoalType.init(rawValue: model.goalType) {
        case .step:
            //目标配速
            //32代表GPS骑行
            self.goalLabel.text = paceString
            self.goalSubLabel.text = "/\(self.returnPaceString(pace: Double(model.goal)))\(Unit.sharedInstance.returnPaceUnit())"
            
            if model.type == 32 {
                self.removeArrangeSubview(subView: self.kcalLabelStackView, in: self.line1StackView)
                self.insertArrangeSubview(subView: self.kcalLabelStackView, in: self.line2StackView, at: 0)
                
                self.removeArrangeSubview(subView: self.paceLabelStackView, in: self.line1StackView)
                self.paceLabelStackView.isHidden = true
                self.addArrangeSubview(subView: distanceStackView, in: self.line1StackView)
                
                self.removeArrangeSubview(subView: self.rateLabelStackView, in: self.line2StackView)
                self.rateLabelStackView.isHidden = true
                self.removeArrangeSubview(subView: self.stepLabelStackView, in: self.line2StackView)
                self.stepLabelStackView.isHidden = true
                
            } else {
                self.removeArrangeSubview(subView: self.paceLabelStackView, in: self.line1StackView)
                self.paceLabelStackView.isHidden = true
                self.insertArrangeSubview(subView: self.distanceStackView, in: self.line1StackView, at: 1)
            }
            break
        case .kcal:
            //目标卡路里
            self.goalLabel.text = kcalString
            self.goalSubLabel.text = "/\(model.goal)\(Unit.sharedInstance.returnKcalUnit())"
            if model.type == 32 {
                self.removeArrangeSubview(subView: self.kcalLabelStackView, in: self.line1StackView)
                self.kcalLabelStackView.isHidden = true
                self.removeArrangeSubview(subView: self.rateLabelStackView, in: self.line2StackView)
                self.rateLabelStackView.isHidden = true
                self.removeArrangeSubview(subView: self.stepLabelStackView, in: self.line2StackView)
                self.stepLabelStackView.isHidden = true
                self.insertArrangeSubview(subView: self.distanceStackView, in: self.line2StackView, at: 0)
            } else {
                self.removeArrangeSubview(subView: self.kcalLabelStackView, in: self.line1StackView)
                self.kcalLabelStackView.isHidden = true
                self.addArrangeSubview(subView: self.distanceStackView, in: self.line1StackView)
            }
            break
        case .exerciseTime:
            //目标时长
            self.goalLabel.text = durationString
            self.goalSubLabel.text = "/\(self.returnDurationString(duration: model.goal))"
            if model.type == 32 {
                self.removeArrangeSubview(subView: self.kcalLabelStackView, in: self.line1StackView)
                self.insertArrangeSubview(subView: self.kcalLabelStackView, in: self.line2StackView, at: 0)
                
                self.removeArrangeSubview(subView: self.timeStackView, in: self.line1StackView)
                self.timeStackView.isHidden = true
                self.insertArrangeSubview(subView: self.distanceStackView, in: self.line1StackView, at: 0)
                
                self.removeArrangeSubview(subView: self.rateLabelStackView, in: self.line2StackView)
                self.rateLabelStackView.isHidden = true
                self.removeArrangeSubview(subView: self.stepLabelStackView, in: self.line2StackView)
                self.stepLabelStackView.isHidden = true
            } else {
                self.removeArrangeSubview(subView: self.timeStackView, in: self.line1StackView)
                self.timeStackView.isHidden = true
                self.insertArrangeSubview(subView: self.distanceStackView, in: self.line1StackView, at: 0)
            }
            break
        case .distance:
            //目标距离
            self.goalLabel.text = distanceString
            self.goalSubLabel.text = "/\(self.returnDistanceString(distance: Double(model.goal)))\(Unit.sharedInstance.getDistanceNameGPS())"
            if model.type == 32 {
                self.removeArrangeSubview(subView: self.kcalLabelStackView, in: self.line1StackView)
                self.insertArrangeSubview(subView: self.kcalLabelStackView, in: self.line2StackView, at: 0)
                
                self.removeArrangeSubview(subView: self.rateLabelStackView, in: self.line2StackView)
                self.rateLabelStackView.isHidden = true
                self.removeArrangeSubview(subView: self.stepLabelStackView, in: self.line2StackView)
                self.stepLabelStackView.isHidden = true
            }
            break
        default:
            self.goalLabel.text = distanceString
            self.goalSubLabel.text = "\(Unit.sharedInstance.getDistanceNameGPS())"
            if model.type == 32 {
                self.removeArrangeSubview(subView: self.kcalLabelStackView, in: self.line1StackView)
                self.insertArrangeSubview(subView: self.kcalLabelStackView, in: self.line2StackView, at: 0)
                
                self.removeArrangeSubview(subView: self.rateLabelStackView, in: self.line2StackView)
                self.rateLabelStackView.isHidden = true
                self.removeArrangeSubview(subView: self.stepLabelStackView, in: self.line2StackView)
                self.stepLabelStackView.isHidden = true
            }
            break
        }
    }
    
    private func removeArrangeSubview(subView: InfoStackView, in superView: UIStackView) {
        if superView.arrangedSubviews.contains(subView) {
            superView.removeArrangedSubview(subView)
        }
    }
    
    private func addArrangeSubview(subView: InfoStackView, in superView: UIStackView) {
        if !superView.arrangedSubviews.contains(subView) {
            superView.addArrangedSubview(subView)
        }
    }
    
    private func insertArrangeSubview(subView: InfoStackView, in superView: UIStackView, at index: Int) {
        if !superView.arrangedSubviews.contains(subView) {
            superView.insertArrangedSubview(subView, at: index)
        }
    }
    
    //MARK: - 算法
    private func calculationPace(distance: Double, duration: Double) -> Double {
        var pace = 0.0
        if distance > 0 {
            pace = (duration / 60.0) / (distance / (Unit.sharedInstance.myType == .metric ? 1000.0 : 1609.3))
        }
        return pace
    }
    
    private func returnPaceString(pace: Double) -> String {
        var paceString = "--'--\""
        if pace > 0.0 {
            paceString = String(format: "%d' %d''",Int(pace), Int((pace * 100)) % 100)
        }
        return paceString
    }
    
    private func returnDurationString(duration: Int) -> String {
        var durationString = "--:--:--"
        if duration >  0 {
            var component: [Double] = [0, 0, 0]
            var t = Double(duration)

            for i in 0 ..< component.count {
                component[i] = Double(Int(t) % 60)
                t /= 60.0
            }

            durationString = NSString(format: "%02d:%02d:%02d", lround(component[2]) , lround(component[1]), lround(component[0])) as String
        }
        return durationString
    }
    
    private func returnDistanceString(distance: Double) -> String {
        let number = Double(distance) / (Unit.sharedInstance.myType == .metric ? 1000.0 : 1609.3)
        let roundedNumber = ceil(number * 100) / 100
        let formattedNumber = String(format: "%.2f", roundedNumber)
        return distance > 0.0 ? "\(formattedNumber)" : "--"
    }
    
    private func returnRateString(step: Double, duration: Double) -> String {
        var rateString = "--"
        if duration > 0.0 && step > 0.0 {
            var rate = 0
            let minute = duration / 60.0
            rate = Int(Double(step)/minute)
            if rate > 0 {
                rateString = rate.normalTitle
            }
        }
        return rateString
    }
    
    
    
    open func setGradientbar(barView: UIView?){
        barView?.layer.sublayers?.forEach({ (subLayer) in
            subLayer.removeFromSuperlayer()
        })
        let layer0 = CAGradientLayer()
        layer0.colors = UIColor.GPSTraining.slowToFastState.map({ $0.cgColor })
        layer0.locations = [0, 0.25, 0.51, 1]
        layer0.startPoint = CGPoint(x: 0.25, y: 0.5)
        layer0.endPoint = CGPoint(x: 0.75, y: 0.5)
        layer0.transform = CATransform3DMakeAffineTransform(CGAffineTransform(a: 1, b: 0, c: 0, d: 28056.25, tx: 0, ty: -14028.12))
        layer0.frame = CGRect(x: 0, y: 0, width: kScreenWidth - 40, height: 4)
        barView?.layer.addSublayer(layer0)
    }
    
    open class InfoStackView: UIStackView{
        
        public let titleLabel: UILabel = {
            let lab = UILabel()
            lab.textColor = .black
            lab.font = .systemFont(ofSize: 16, weight: .heavy)
            lab.height = 16
            return lab
        }()
        public let subLabel: UILabel = {
            let lab = UILabel()
            lab.textColor = .black
            lab.font = .systemFont(ofSize: 12)
            return lab
        }()
        
        public required init(_ isHeart: Bool = false) {
            super.init(frame: CGRect.zero)
            makeUI(isHeart)
            
        }
        
        public override init(frame: CGRect) {
            super.init(frame: frame)
            makeUI()
        }
        
        public required init(coder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
        
        open func makeUI(_ isHeart: Bool = false) {
            
            if isHeart{
                let heartImage = UIImageView(frame: CGRect(x: 0, y: 0, width: 11, height: 10.5))
                heartImage.image = UIImage(named: "ic_gps_exercise_hr")
                let stackView = UIStackView(arrangedSubviews: [heartImage,titleLabel])
                stackView.distribution = .fill
                stackView.axis = .horizontal
                stackView.alignment = .center
                stackView.spacing = 2
                self.addArrangedSubview(stackView)
            }else {
                self.addArrangedSubview(titleLabel)
            }
            
            self.addArrangedSubview(subLabel)
            distribution = .fillEqually
            axis = .vertical
            alignment = .center
            spacing = 3
        }
        
        public func setTitle(title: String){
            titleLabel.text = title
        }
        
        public func setSubTitle(subTitle: String){
            subLabel.text = subTitle
        }
    }

}
